package model

import (
	"gorm.io/gorm"
	"strconv"
	"time"
)

type Room struct {
	gorm.Model
	Name        string     `json:"name"`
	CreatorID   string     `json:"creator_id"`
	CreatorName string     `json:"creator_name"`
	EmptySince  *time.Time `json:"empty_since"`
	IsMatching  bool       `json:"is_matching"`
	Tag         string     `json:"tag"`
}

func CreateRoom(db *gorm.DB, room *Room) error {
	return db.Create(room).Error
}

func GetAllRooms(db *gorm.DB) ([]Room, error) {
	var rooms []Room
	err := db.Find(&rooms).Error
	return rooms, err
}

func DeleteRoomByID(db *gorm.DB, id string) error {
	var roomID uint
	if n, err := strconv.ParseUint(id, 10, 32); err == nil {
		roomID = uint(n)
	} else {
		return err
	}
	return db.Delete(&Room{}, roomID).Error
}

func SetRoomEmptySince(db *gorm.DB, id string, t time.Time) error {
	var roomID uint
	if n, err := strconv.ParseUint(id, 10, 32); err == nil {
		roomID = uint(n)
	} else {
		return err
	}
	return db.Model(&Room{}).Where("id = ?", roomID).Update("empty_since", t).Error
}

func ClearRoomEmptySince(db *gorm.DB, id string) error {
	var roomID uint
	if n, err := strconv.ParseUint(id, 10, 32); err == nil {
		roomID = uint(n)
	} else {
		return err
	}
	return db.Model(&Room{}).Where("id = ?", roomID).Update("empty_since", nil).Error
}

func DeleteRoomByNameAndCreator(db *gorm.DB, name, creatorID string) error {
	return db.Delete(&Room{}, "name = ? AND creator_id = ?", name, creatorID).Error
}

func SetRoomEmptySinceByNameAndCreator(db *gorm.DB, name, creatorID string, t time.Time) error {
	return db.Model(&Room{}).Where("name = ? AND creator_id = ?", name, creatorID).Update("empty_since", t).Error
}

func ClearRoomEmptySinceByNameAndCreator(db *gorm.DB, name, creatorID string) error {
	return db.Model(&Room{}).Where("name = ? AND creator_id = ?", name, creatorID).Update("empty_since", nil).Error
}

func GetAllMatchingRooms(db *gorm.DB, name string) ([]Room, error) {
	var rooms []Room
	err := db.Where("name = ? AND is_matching = ?", name, true).Find(&rooms).Error
	return rooms, err
}
